from __future__ import absolute_import
from os.path import join
from forest.api import Command, get_tool
from forest.resources.mount import Fstab, BlockIds

class FstabCommand(Command):
    ''' Creates an fstab in the install root using all available mount resources.
    '''
    __register__ = 'commands.setup.Fstab'

    block_ids_class = BlockIds
    
    def set_block_ids_class(self, cls):
        self.block_ids_class = cls
        
    def run(self, config):
        fstab_path = config.join_install_root('etc','fstab')

        Command.SIGNAL_COMMAND_PROGRESS(self, message='Starting creation of filesystem table.')
        mounts = list(config.get_resources().iter_by_type('mount'))
        
        if not mounts:
            pass
        
        fstab = Fstab(config, self.block_ids_class)
        fstab_lines = fstab.get_lines()
        if not fstab_lines:
            raise Exception("Fstab does not contain any lines")

        fstab_lines.append('')
        
        get_tool('files.write')(fstab_path, '\n'.join(fstab_lines))


